import { EResType } from "../../../Script/Common/Enum";
import { ILotteryGrade } from "../../../Script/Common/GlobalData";
import { IFlyResData } from "../../../Script/Interface/IMessage";
import { SceneGame } from "../../../Script/SceneGame";
import GameUtil from "../../../Script/Util/GameUtil";
import Eraser from "./Eraser";

interface IRewardData {
    /** iconid */
    id: number;
    /** 奖励金额 */
    value?: number[];
    /** 奖励索引 */
    pos?: number[];
}

const { ccclass, property } = cc._decorator;

@ccclass
export default class Mountain extends Eraser {

    @property({ type: cc.Node, tooltip: "刮刮乐对照点" })
    protected compare: cc.Node = null;

    @property({ type: cc.Node, tooltip: "奖励金额节点" })
    protected rewardNums: cc.Node = null;

    /** 中奖对照数据 */
    private reward: IRewardData = { id: -1, value: [], pos: [] };
    private nums: number[] = [];

    public restart() {
        super.restart();

        this.nums = [];
        this.reward = { id: -1, value: [], pos: [] };

        const p = Math.random() * 100;
        if (p <= this.data.p) { // 中奖
            // 小额最多中奖4次
            const num = Math.ceil(Math.random() * this.grade.max);
            const arr = this.getIndexArr();
            const indexs = GameUtil.getRandomElement(arr, num);
            this.refreshItems(indexs, this.grade);

            console.log("中奖--", this.grade.id, '---', num);
        } else {
            this.refreshItems([], this.grade);

            console.log("未中奖~");
        }
    }

    private refreshItems(indexs: number[], grade: ILotteryGrade) {
        // 刷新奖励金额
        this.rewardNums.children.forEach((o) => {
            this.positions.push(cc.v2(o.x, o.y));  // TODO 是否需要刮出
            const value = this.random(this.totalArr);
            const num = cc.find("num", o).getComponent(cc.Label);
            num.string = `${GameUtil.changeUnit(value, 0)}`;
            this.nums.push(value);
        });

        // 中奖号码
        this.reward.id = this.random(99) + 1;
        this.refreshItem(this.compare, this.reward);

        const arr = this.exclude();
        this.items.children.forEach((o, i) => {
            this.positions.push(cc.v2(o.x, o.y));
            this.refreshItem(o, { id: this.random(arr) });
        });
        this.positionProgress = new Array(this.positions.length);

        // 重刷中奖展示
        for (let k = 0; k < indexs.length; k++) {
            const index = indexs[k];
            const node = this.items.children[index];
            this.refreshItem(node, this.reward);

            const g = this.getRewardGroup(indexs[k]);
            this.reward.value.push(this.nums[g]);
        }
        this.reward.pos = indexs;
    }

    private getRewardGroup(index: number) {
        let id = index + 1;
        let arr = [1, 2, 3, 4, 5, 5];
        for (let i = 0; i < arr.length; i++) {
            if (id >= arr[i]) {
                id -= arr[i];
                if (id <= 0) {
                    return i;
                }
            } else {
                return i;
            }
        }
    }

    /** 兑奖 */
    protected async checkReward() {
        try {
            super.checkReward();
            const len = this.reward.pos.length;
            if (len > 0) {
                for (let i = 0; i < len; i++) {
                    const index = this.reward.pos[i];
                    const value = this.reward.value[i];
                    const data = SceneGame.instance.getFlyResData();
                    const flyData: IFlyResData = {
                        resType: EResType.Money,
                        parent: data.flyNode,
                        from: this.items.children[index],
                        to: data.money,
                        value: value,
                        flyTimes: 10,
                        maxWidth: 60,
                        maxHeight: 60,
                    }
                    GameUtil.instance.flyResIcon(flyData);
                    console.log(`动物id:${this.reward.id}  中奖金额:${value}  位置: ${index}`);
                    await GameUtil.sleep(200);
                }
            } else {
                console.log("未中奖~");
            }
        } catch (error) {
            console.log(error);
        }
    }

    private getIndexArr() {
        const temp: number[] = [];
        const len = this.items.children.length;
        for (let i = 0; i < len; i++) {
            temp.push(i);
        }
        return temp;
    }

    private exclude() {
        const ex = [];
        for (let i = 1; i < 100; i++) {
            if (i !== this.reward.id) {
                ex.push(i);
            }
        }
        return ex;
    }

    private refreshItem(node: cc.Node, data: IRewardData) {
        try {
            const num = node.getComponent(cc.Label);
            num.string = `${data.id}`;
        } catch {
            console.log(node, data);
        }
    }
}